package com.idbk.chargestation.activity.charge;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.idbk.chargestation.amap.util.AMapResultCode;
import com.android.volley.VolleyError;
import com.idbk.chargestation.R;
import com.idbk.chargestation.api.ChargeStationAPI;
import com.idbk.chargestation.amap.base.BaseMapGeographyActivity;
import com.idbk.chargestation.bean.JsonBase;
import com.idbk.chargestation.dialog.DialogTranslucent;
import com.idbk.chargestation.net.EHttpResponse;
import com.idbk.chargestation.util.Const;
import com.idbk.chargestation.util.GsonUtils;

import java.util.Locale;

/**
 * 纠错--地理信息
 *
 * @author zhx
 */
public class ActivityCorrectGeography extends BaseMapGeographyActivity {

    public final static String TAG = ActivityCorrectGeography.class.getSimpleName();
    private Context mContext;
    private TextView mTextLat, mTextLng, mTextAddress;
    private String mAddress, mCity, mProvince, mCountry;
    private double mLat, mLng;
    private int mPointId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_correct_geography);

        initView(savedInstanceState);

        initData();
    }

    private void initView(Bundle savedInstanceState) {
        setupToolBar2();
        mContext = this;
        initTextView();
        initMapView(savedInstanceState);
        setCameraChangeListener();
        initLocationStyle();
        initGeocodeSearch();
    }

    @SuppressWarnings("ConstantConditions")
    private void initTextView() {
        mTextAddress = (TextView) findViewById(R.id.textview_address);
        mTextLat = (TextView) findViewById(R.id.textview_lat);
        mTextLng = (TextView) findViewById(R.id.textview_lng);

        findViewById(R.id.textview_submit).setOnClickListener(this);
    }

    private void initData() {
        mPointId = getIntent().getIntExtra(Const.KEY_ID, -1);
        if (mPointId == -1) {
            Toast.makeText(mContext, "传入参数错误", Toast.LENGTH_LONG).show();
            finish();
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.textview_submit) {
            submit();
        }
    }

    private void submit() {
        if (checkInput()) {
            submitData();
        } else {
            showErrorDialog("处理失败", "请先获取正确的地理信息！");
        }
    }

    private void submitData() {
        if (mPointId != -1) {
            showMyProgressDialog(true, true, "提交中...");
            mMainRequest = ChargeStationAPI.correctPointGeography(
                    mPointId, mLat, mLng, mProvince, mCity, mCountry, mAddress, mResponse);
        }
    }

    private void showErrorDialog(String eResult, String eTip) {
        DialogTranslucent dialog = new DialogTranslucent(mContext, null, eResult, eTip);
        dialog.show();
    }

    private boolean checkInput() {
        if (mLat == 0 || mLng == 0) {
            return false;
        }
        if (checkInputEmpty()) {
            return false;
        }
        return true;
    }

    private boolean checkInputEmpty() {
        return mAddress == null || mProvince == null
                || mCity == null || mCountry == null;
    }

    private final EHttpResponse mResponse = new EHttpResponse() {

        @Override
        public void onEResponse(String response) {
            JsonBase result = GsonUtils.toBean(JsonBase.class, response);
            if (handleResponseStatus(result)) {
                DialogTranslucent dialog = new DialogTranslucent(mContext,
                        ContextCompat.getDrawable(mContext, R.drawable.ico_toast_success),
                        "提交成功",
                        "感谢你的大力支持！");
                dialog.show();
                //提交成功后直接返回到主界面
                dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        finish();
                    }
                });
            }
        }

        @Override
        public void onEErrorResponse(VolleyError error) {
            super.onEErrorResponse(error);
            showErrorDialog("提交失败", "网络连接失败！");
        }

        @Override
        public void onEFinish() {
            super.onEFinish();
            dismissMyProgressDialog();
        }

    };

    @Override
    public void onCameraChange(CameraPosition position) {
        Log.e(TAG, "onCameraChange: ");
        mTextAddress.setText("获取当前地址中…");
        LatLng latLng = position.target;//获取屏幕中心点
        mLng = latLng.longitude;
        mLat = latLng.latitude;
        mTextLng.setText(String.format(Locale.CHINA, "经度：%.6f", mLng));
        mTextLat.setText(String.format(Locale.CHINA, "纬度：%.6f", mLat));
    }

    @Override
    public void onCameraChangeFinish(CameraPosition position) {
        LatLng latLng = position.target;//获取屏幕中心点
        RegeocodeQuery query = new RegeocodeQuery(new LatLonPoint(latLng.latitude, latLng.longitude),
                200, GeocodeSearch.AMAP);
        mGeocodeSearch.getFromLocationAsyn(query);
    }

    @Override
    public void onGeocodeSearched(GeocodeResult arg0, int arg1) {

    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
        if (rCode == AMapResultCode.OK) {  //正常返回
            if (result != null && result.getRegeocodeAddress() != null &&
                    result.getRegeocodeAddress().getFormatAddress() != null) {
                String addressName = result.getRegeocodeAddress().getFormatAddress();
                Log.d(TAG, result.getRegeocodeAddress().getTownship());
                Log.d(TAG, result.getRegeocodeAddress().getStreetNumber().getStreet());
                mTextAddress.setText(addressName);
                mProvince = result.getRegeocodeAddress().getProvince();
                mCity = result.getRegeocodeAddress().getCity();
                mCountry = result.getRegeocodeAddress().getDistrict();
                if (addressName.contains(mProvince)) {
                    addressName = addressName.replace(mProvince, "");
                }
                if (addressName.contains(mCity)) {
                    addressName = addressName.replace(mCity, "");
                }
                mAddress = addressName;
                Log.d(TAG, addressName);
            }
        }
    }

}
